package com.study.spring.netty.time_server;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @author zhang
 * @version 1.0
 * @date 2019/5/7 0007
 * @since jdk1.8
 */
public class TimeServerDecode extends ByteToMessageDecoder {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf byteBuf, List<Object> out) throws Exception {
        byteBuf.markReaderIndex();
        int start = byteBuf.readInt();
        if (start == 0xAA) {
            int length = byteBuf.readInt();
            if (byteBuf.readableBytes() >= length + 4) {
                CharSequence quest = byteBuf.readCharSequence(length, StandardCharsets.UTF_8);
                System.out.println(quest);
                out.add(quest);
                byteBuf.readInt();
            } else {
                byteBuf.resetReaderIndex();
            }
        } else {
            byteBuf.clear();
            out.add("error                                                                     msg start:" + start);
        }
    }
}
